
var ItemTracking = new Class({
    Implements: Options,
    options: {
        'tagid':''
    },
    panel: null,
    content: null,
    listData: null,
    result:null,
    initialize: function(opts) {
        this.setOptions(opts);

        this.panel = document.id(this.options.tagid);
        if(!this.panel) return;
        this.panel.empty();

        this.createTable();
        this.createHead();

        this.itemTrackingRequest = new Request({
            url: '/Admin/webstat/getFromMySQL',
            method: 'get',
            onRequest: function() {
                new ShowBox().say('Loading...');
                new Loader().show();
            },
            onComplete: function(resp) {
                var data = [];
                try {
                    data = eval('[' + resp + ']');
                }
                catch(err) { alert('Error...\n' + err); return; }
                new Loader().hide();

                this.fillContent(data);
            }.bind(this)
        }).send('table=ittrack&ex=getAdv&nc=' + Date.now());

    },
    createTable: function() {
        this.content = new Element('div#content');
        this.listData = new Element('table#listData',{'rules':'groups'});

        this.panel.adopt(
            new Element('div.tl[html=<div class="tr"><div>&nbsp;</div></div>]'),
            this.content.adopt(this.listData),
            new Element('div.bl[html=<div class="br"><div>&nbsp;</div></div>]')
        );
    },
    createHead: function() {
        this.listData.adopt(
            new Element('thead').adopt(
                new Element('tr', { html:
                    '<th class="brdCol w15">&nbsp;</th><th class="brdCol w15">&nbsp;</th><th class="brdCol w150">Advert Name</th>' +
                    '<th class="brdCol w50">Hits</th><th class="brdCol w50">Orders</th><th class="brdCol w50">Rating</th><th class="brdCol w50">Amount</th>'
                })
            ),
            new Element('tfoot').adopt(
                new Element('tr').adopt(
                    new Element('th.tdFull[html=&nbsp;]', {'colspan': 7})
                )
            ),
            new Element('tbody')
        );
    },
    fillContent: function(data) {
        var advert,tbody,tr,tdo,tde,color=false,tagid;

        tbody = this.listData.getElement('tbody');
        tbody.empty();

        for(var i = 0; i < data.length; i++) {
            advert = data[i];

            tr = new Element('tr[style=background-color:#' + ((color = !color) ? 'ffffff' : 'fcffcd') + ';]',{
                'events': {
                    'mouseenter': function() {this.addClass('rowHover');},
                    'mouseleave': function() {this.removeClass('rowHover');}
                }
            });

            tagid = 'git_' + i;
            tdo = new Element('td.imgCol').adopt(
                new Element('a.' + (advert.act ? 'plus' : 'disalow') + '[href=javascript:;][html=&nbsp;][title=Open Category]',{
                    'events': {
                        'click': advert.act ? this.makeCategory.bind(this, advert.aid, tagid) : function(){},
                        'focus': function() {this.blur();}
                    }
                })
            );
            tde = new Element('td.imgCol').adopt(
                new Element('a.edit[href=javascript:;][html=&nbsp;][title=Edit advert]',{
                    'events': {
                        'focus': function() {this.blur();}
                    }
                })
            );

            tbody.adopt(
                tr.adopt(
                    tdo,
                    tde,
                    new Element('td.brdCol.w150' + (advert.act ? '' : '.silver') + '[text=' + advert.name + ']'),
                    new Element('td.brdCol.center.w50[text=' + (advert.hits ? advert.hits : ' ') + ']'),
                    new Element('td.brdCol.center.w50[text=' + (advert.orders ? advert.orders : ' ') + ']'),
                    new Element('td.brdCol.center.w50[html=&nbsp;]'),
                    new Element('td.brdCol.center.w50[text=' + (advert.amount ? '$' + numberFormat(advert.amount) : ' ') + ']')
                )
            );

            tbody.adopt(
                new Element('tr#x' + tagid + '[style=display:none]').adopt(
                    new Element('td[html=&nbsp;]'),
                    new Element('td#d' + tagid + '[colspan=7][style=padding-top:0]')
                )
            );

        }// for

    },
    makeCategory: function(advertid, tagid, ev) {

        this.advertid = advertid;

        var xcuc = document.id('x' + tagid);
        var dcuc = document.id('d' + tagid);
        if(ev.target.hasClass('plus')) {
            ev.target.removeClass('plus').addClass('minus');

            dcuc.empty();
            var div = new Element('div#gcat').inject(dcuc);

            this.categoryRequest = new Request({
                url: '/Admin/webstat/getFromMySQL',
                method: 'get',
                onRequest: function() {
                    ev.target.addClass('load');
                },
                onComplete: function(resp) {
                    var data = [];
                    try {
                        data = eval('[' + resp + ']');
                    }
                    catch(err) { alert('Error...\n' + err); return; }
                    ev.target.removeClass('load');

                    this.showCategory(data, div);
                }.bind(this)
            }).send('table=ittrack&ex=getcat&nc=' + Date.now());

            xcuc.set('styles', {'display': '', 'background-color': '#ffffff'});
        }
        else {
            ev.target.removeClass('minus').addClass('plus');

            xcuc.setStyle('display', 'none');
        }
    },
    showCategory: function(data, tagid) {

        tagid.empty();

        var divsub = new Element('div');
        var divcat = new Element('div');
        for(var i = 0; i < data.length; i++) {
            divcat.adopt(
                new  Element('tt[text=[]'),
                new  Element('a[href=javascript:;][text=' + data[i].name + ']',{
                    'events': {
                        'click': this.getSubcat.bind(this, data[i].id, data[i].name, divsub),
                        'focus': function() {this.blur();}
                    }
                }),
                new  Element('tt[text=]]')
            );
        }
        tagid.adopt(divcat, divsub);
    },
    getSubcat: function(catid, catName, tagid) {

        this.categoryid = catid;
        tagid.empty();

        this.subcatRequest = new Request({
            url: '/Admin/webstat/getFromMySQL',
            method: 'get',
            onRequest: function() {
                new ShowBox().say('Opening...');
                new Loader().show();
            },
            onComplete: function(resp) {
                var data = [];
                try {
                    data = eval('(' + resp + ')');
                }
                catch(err) { alert('Error...\n' + err); return; }
                new Loader().hide();

                this.showSubcategory(data, tagid, catName);
            }.bind(this)
        }).send('table=ittrack&ex=getscat&aid=' + this.advertid + '&cid=' + catid + '&nc=' + Date.now());

    },
    showSubcategory: function(data, tagid, catName) {

        var adverts = new Hash(), cats = new Hash(), legend = '';
        data.sub.each(function(subcat) {
            if(!adverts.has(subcat.alias)) {
                adverts.set(subcat.alias, subcat.vid);
                legend += '(<tt>' + subcat.alias + '</tt> - <em>' + subcat.vname + '</em>), ';
            }
            //
            if(!cats.has(subcat.cname)) {
                cats.set(subcat.cname,subcat.cid);
            }

        });
        //
        tagid.adopt(
            new  Element('hr'),
            new  Element('tt[text=' + catName + '][style=color:#800000;font-weight:bold;]'),
            new  Element('div#legend[html=<b>Legend:</b> ' + legend + ']')
        );

        var tbody = new Element('tbody'),td,trd,haveBorder = false,catSum=0,catAmnt=0,cbox,chk,notGroup;
        var trhead = new Element('tr').adopt(
            new Element('th.brdCol.left.w50').adopt(
                new Element('tt[text=Subcategory]'),
                new Element('br'),
                new Element('input[type=checkbox]',{
                    'events': {
                        'click': this.groupAllToggle.bind(this),
                        'focus': function() {this.blur();}
                    }
                }).store('grp', this.advertid)
            )
        );
        var trbot = new Element('tr').adopt(
            new Element('th.brdCol.left.w50').adopt(
                new  Element('button[text= Save ]',{
                    'events': {
                        'click': this.saveGroup.bind(this),
                        'focus': function() {this.blur();}
                    }
                }).store('grp', this.advertid)
            )
        );

        cats.each(function(catid, catName) {
            trd = new Element('tr').adopt(
                new Element('td.brdCol.left.w50[html=<h4>' + catName + '</h4>]')
            );

            catSum = 0;
            adverts.each(function(vendid, vendAlias) {
                cbox = this.getCheckBox(data.sub, catid, vendid);
                chk =  this.getCheckGroup(data.grp, catid, vendid);
                notGroup = chk.gid !== this.advertid;

                td = new Element('td.brdCol.center.w15[html=&nbsp;]');
                if(cbox.cnt) {
                    td.set('html','<b style="cursor:pointer;" title="' + (notGroup ? chk.names: 'here') + '">' + cbox.cnt + '</b><br/>' +
                           '<input ' +
                           (notGroup ? '' : 'checked="checked"') + ' name="' + this.advertid + '_' + vendid + '" value="' + catid + '_' + vendid + '" type="checkbox" />');

                    catSum += cbox.cnt;
                }
                trd.adopt(td);

                if(!haveBorder) {
                    trhead.adopt(
                        new Element('th.brdCol.center.w15').adopt(
                            new Element('tt[text=' + vendAlias + ']'),
                            new Element('br'),
                            new Element('input#' + (this.advertid + '_' + vendid) + '[type=checkbox]',{
                                'events': {
                                    'click': this.groupToggle.bind(this),
                                    'focus': function() {this.blur();}
                                }
                            })
                        )
                    );
                    catAmnt += catSum;
                    trbot.adopt(
                        new Element('th.brdCol.center.w15[html=<b>&nbsp;</b>]')
                    );
                }
            }, this);
            haveBorder = true;
            trd.adopt(
                new Element('td.brdCol.center.w15[html=<b>' + catSum + '</b>]')
            );
            tbody.adopt(trd);
        }, this);

        trhead.adopt(
            new Element('th.brdCol.center.w15[html=&nbsp;]')
        );
        trbot.adopt(
            new Element('th.brdCol.center.w15[html=<b>' + catAmnt + '</b>]')
        );

        this.subTable = new Element('table#listData]', {'rules':'groups'});
        this.subTable.adopt(
            new Element('thead').adopt(trhead),
            new Element('tfoot').adopt(trbot),
            tbody
        );
        tagid.adopt(this.subTable);

    },
    getCheckBox: function(cats, cid, vid) {
        var result = {};
        for(var i = 0; i < cats.length; i++) {
            if(cats[i].cid === cid && cats[i].vid === vid) {
                result = {als:cats[i].alias,cnt:cats[i].cnt};
                break;
            }
        }
        return result;
    },
    getCheckGroup: function(grps, cid, vid) {
        var result = {}, /*names = '', idx = 0,*/ notFind = true;
        for(var i = 0; i < grps.length; i++) {
            if(grps[i].cid === cid && grps[i].vid === vid) {
                if(notFind) {
                    notFind = false;
                    result = {names: '', gid: grps[i].gid, vid: grps[i].vid, cid: grps[i].cid};
                }
            }
        }
        return result;
    },
    groupToggle: function(ev) {
        var checkme = this.subTable.getElements('input[name=' + ev.target.get('id') + ']'), docheck;
        if(ev.target.retrieve('togg')) {
            docheck = false;
            ev.target.store('togg', docheck);
        }
        else {
            docheck = true;
            ev.target.store('togg', docheck);
        }
        checkme.each(function(el) {
            el.set('checked', docheck);
        });
    },
    groupAllToggle: function(ev) {
        var checkme = this.subTable.getElements('input[name^=' + ev.target.retrieve('grp') + ']'),docheck;
        if(ev.target.retrieve('togg')) {
            docheck = false;
            ev.target.store('togg', docheck);
        }
        else {
            docheck = true;
            ev.target.store('togg', docheck);
        }
        checkme.each(function(el) {
            el.set('checked', docheck);
        });
    },
    saveGroup: function(ev) {

        var checkme = this.subTable.getElements('input[name^=' + ev.target.retrieve('grp') + ']');
        var val = '&cb=';
        checkme.each(function(el,idx) {
            val += (idx++ > 0 ? ',' : '') + el.get('value') + '_' + (el.get('checked') ? 1 : 0);
        });

        this.saveRequest = new Request({
            url: '/Admin/webstat/getFromMySQL',
            method: 'post',
            onRequest: function() {
                new ShowBox().say('Saving...');
                new Loader().show();
            },
            onComplete: function() {
                new Loader().hide();
            }
        }).send('table=ittrack&ex=save&aid=' + this.advertid + '&cid=' + this.categoryid + '&nc=' + Date.now() + val);
    }

});
